{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "d4co3_i434-C"
   },
   "source": [
    "##### Copyright 2020 The Cirq Developers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "form",
    "id": "2u6HZdKb4RXV"
   },
   "outputs": [],
   "source": [
    "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "# https://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Y2uPCv_O43wN"
   },
   "source": [
    "# Notebook template"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "8w2UKUVC4rs6"
   },
   "source": [
    "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://quantumai.google/cirq/tutorials/google/colab\"><img src=\"https://quantumai.google/site-assets/images/buttons/quantumai_logo_1x.png\" />View on QuantumAI</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/Cirq/blob/main/docs/tutorials/google/colab.ipynb\"><img src=\"https://quantumai.google/site-assets/images/buttons/colab_logo_1x.png\" />Run in Google Colab</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://github.com/quantumlib/Cirq/blob/main/docs/tutorials/google/colab.ipynb\"><img src=\"https://quantumai.google/site-assets/images/buttons/github_logo_1x.png\" />View source on GitHub</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a href=\"https://storage.googleapis.com/tensorflow_docs/Cirq/docs/tutorials/google/colab.ipynb\"><img src=\"https://quantumai.google/site-assets/images/buttons/download_icon_1x.png\" />Download notebook</a>\n",
    "  </td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "fe7e28f44667"
   },
   "source": [
    "## Setup\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "bd9529db1c0b"
   },
   "outputs": [],
   "source": [
    "try:\n",
    "    import cirq\n",
    "    import cirq_google\n",
    "except ImportError:\n",
    "    print(\"installing cirq...\")\n",
    "    !pip install --quiet cirq-google\n",
    "    print(\"installed cirq.\")\n",
    "    import cirq\n",
    "    import cirq_google"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "iBW4Iix64cFn"
   },
   "source": [
    "## Make a copy of this template\n",
    "\n",
    "You will need to have access to Quantum Computing Service before running this colab.\n",
    "\n",
    "This notebook can serve as a starter kit for you to run programs on Google's quantum hardware.  You can download it using the directions below, open it in colab (or Jupyter), and modify it to begin your experiments."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "6q5lpwgW5TrE"
   },
   "source": [
    "## How to download iPython notebooks from GitHub\n",
    "\n",
    "You can retrieve iPython notebooks in the Cirq repository by\n",
    "going to the [docs/ directory](https://github.com/quantumlib/Cirq/tree/main/docs).  For instance, this Colab template is found [here](https://github.com/quantumlib/Cirq/blob/main/docs/tutorials/google/colab.ipynb). Select the file that you would like to download and then click the *Raw* button in the upper-right part of the window:\n",
    "\n",
    "<img src=\"https://raw.githubusercontent.com/quantumlib/Cirq/main/docs/images/colab_github.png\" alt=\"GitHub UI button to view raw file\">\n",
    "\n",
    "This will show the entire file contents.  Right-click and select *Save as* to save this file to your computer.  Make sure to save to a file with a `.ipynb` extension (you may need to select *All files* from the format dropdown instead of *text*). You can also get to this Colab's [raw content directly](https://raw.githubusercontent.com/quantumlib/Cirq/main/docs/tutorials/google/colab.ipynb)\n",
    "\n",
    "You can also retrieve the entire Cirq repository by running the following command in a terminal that has `git` installed:\n",
    "\n",
    "```\n",
    "git clone https://github.com/quantumlib/Cirq.git\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "czt1fSEHooF9"
   },
   "source": [
    "## How to open Google Colab\n",
    "\n",
    "You can open a new Colab notebook from your Google Drive window or by visiting the [Colab site](https://colab.research.google.com/notebooks/intro.ipynb).  From the Colaboratory site, you can use the menu to upload an iPython notebook:\n",
    "\n",
    "<img src=\"https://raw.githubusercontent.com/quantumlib/Cirq/main/docs/images/colab_upload.png\" alt=\"Google Colab's upload notebook entry in File menu.\">\n",
    "\n",
    "This will upload the ipynb file that you downloaded before.  You can now run all the commands, modify it to suit your goals, and share it with others.\n",
    "\n",
    "### More Documentation Links\n",
    "\n",
    "* [Quantum Engine concepts](../../google/concepts.ipynb)\n",
    "* [Quantum Engine documentation](../../google/engine.md)\n",
    "* [Cirq documentation](https://quantumai.google/cirq)\n",
    "* [Colab documentation](https://colab.research.google.com/notebooks/welcome.ipynb)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Bip6ZAIQ6min"
   },
   "source": [
    "## Authenticate with Quantum Computing Service and install Cirq\n",
    "\n",
    "For details of authentication and installation, please see [Get started with Quantum Computing Service](start.ipynb).\n",
    "\n",
    "Note:  The below code will install the latest stable release of Cirq.  If you need the latest and greatest features and don't mind if a few things aren't quite working correctly, you can install the pre-release version of `cirq` using `pip install --upgrade cirq~=1.0.dev` instead of `pip install cirq` to get the most up-to-date features of Cirq.\n",
    "\n",
    "1. Enter the Cloud project ID you'd like to use in the `project_id` field.\n",
    "2. Then run the cell below (and go through the auth flow for access to the project id you entered).\n",
    "\n",
    "<img src=\"https://raw.githubusercontent.com/quantumlib/Cirq/main/docs/images/run-code-block.png\" alt=\"Quantum Engine console\">"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "wfHdoHW67EGh"
   },
   "outputs": [],
   "source": [
    "# The Google Cloud Project id to use.\n",
    "project_id = ''  # @param {type:\"string\"}\n",
    "processor_id = \"\"  # @param {type:\"string\"}\n",
    "\n",
    "from cirq_google.engine.qcs_notebook import get_qcs_objects_for_notebook\n",
    "\n",
    "# For real engine instances, delete 'virtual=True' below.\n",
    "qcs_objects = get_qcs_objects_for_notebook(project_id, processor_id, virtual=True)\n",
    "engine = qcs_objects.engine\n",
    "processor_id = qcs_objects.processor_id"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "5mwzenpB8FYi"
   },
   "source": [
    "## Create an Engine variable\n",
    "\n",
    "The following creates an engine variable which can be used to run programs under the project ID you entered above."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "HCb_9m_o8KEK"
   },
   "outputs": [],
   "source": [
    "from google.auth.exceptions import DefaultCredentialsError\n",
    "from google.api_core.exceptions import PermissionDenied\n",
    "\n",
    "# Create an Engine object to use, providing the project id and the args\n",
    "try:\n",
    "    if qcs_objects.signed_in:  # This line only needed for colab testing.\n",
    "        engine = cirq_google.get_engine()\n",
    "    print(f\"Successful authentication using project {project_id}!\")\n",
    "    print('Available Processors: ')\n",
    "    print(engine.list_processors())\n",
    "    print(f'Using processor: {processor_id}')\n",
    "    processor = engine.get_processor(processor_id)\n",
    "except DefaultCredentialsError as err:\n",
    "    print(\"Could not authenticate to Google Quantum Computing Service.\")\n",
    "    print(\" Tips: If you are using Colab: make sure the previous cell was executed successfully.\")\n",
    "    print(\n",
    "        \"       If this notebook is not in Colab (e.g. Jupyter notebook), make sure gcloud is installed and `gcloud auth application-default login` was executed.\"\n",
    "    )\n",
    "    print()\n",
    "    print(\"Error message:\")\n",
    "    print(err)\n",
    "except PermissionDenied as err:\n",
    "    print(\n",
    "        f\"While you are authenticated to Google Cloud it seems the project '{project_id}' does not exist or does not have the Quantum Engine API enabled.\"\n",
    "    )\n",
    "    print(\"Error message:\")\n",
    "    print(err)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "XEG4t_2b8dYx"
   },
   "source": [
    "## Example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "xujtwGxt8fOA"
   },
   "outputs": [],
   "source": [
    "# A simple example.\n",
    "q = cirq.GridQubit(5, 2)\n",
    "circuit = cirq.Circuit(cirq.X(q) ** 0.5, cirq.measure(q, key='m'))\n",
    "\n",
    "job = processor.run_sweep(program=circuit, repetitions=1000)\n",
    "\n",
    "results = [str(int(b)) for b in job.results()[0].measurements['m'][:, 0]]\n",
    "print('Success!  Results:')\n",
    "print(''.join(results))"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [],
   "name": "colab.ipynb",
   "toc_visible": true
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
